Use AutoAI and Lale to predict credit risk with ibm-watson-machine-learning

This notebook contains the steps and code to demonstrate support of AutoAI experiments in Watson Machine Learning service. It introduces commands for data retrieval, training experiments, persisting pipelines, testing pipelines, refining pipelines, and scoring.

Some familiarity with Python is helpful. This notebook uses Python 3.8.

Learning goals

The learning goals of this notebook are:

Contents

This notebook contains the following parts:

  1. Setup
  2. Optimizer definition
  3. Experiment Run
  4. Pipelines comparison and testing
  5. Historical runs
  6. Pipeline refinement and testing
  7. Deploy and Score
  8. Cleanup
  9. Summary and next steps

1. Set up the environment

Before you use the sample code in this notebook, you must perform the following setup tasks:

Connection to WML

Authenticate the Watson Machine Learning service on IBM Cloud. You need to provide Cloud API key and location.

Tip: Your Cloud API key can be generated by going to the Users section of the Cloud console. From that page, click your name, scroll down to the API Keys section, and click Create an IBM Cloud API key. Give your key a name and click Create, then copy the created key and paste it below. You can also get a service specific url by going to the Endpoint URLs section of the Watson Machine Learning docs. You can check your instance location in your Watson Machine Learning (WML) Service instance details.

You can use IBM Cloud CLI to retrieve the instance location.

ibmcloud login --apikey API_KEY -a https://cloud.ibm.com
ibmcloud resource service-instance WML_INSTANCE_NAME

NOTE: You can also get a service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, and then copy the created key and paste it in the following cell.

Action: Enter your api_key and location in the following cell.

Install and import the ibm-watson-machine-learning and dependecies

Note: ibm-watson-machine-learning documentation can be found here.

Working with spaces

You need to create a space that will be used for your work. If you do not have a space, you can use Deployment Spaces Dashboard to create one.

Tip: You can also use SDK to prepare the space for your work. More information can be found here.

Action: assign space ID below

You can use the list method to print all existing spaces.

To be able to interact with all resources available in Watson Machine Learning, you need to set the space which you will be using.

Connections to COS

In next cell we read the COS credentials from the space.

2. Optimizer definition

Training data connection

Define connection information to COS bucket and training data CSV file. This example uses the German Credit Risk dataset.

The code in next cell uploads training data to the bucket.

Download training data from git repository.

Create connection

Note: The above connection can be initialized alternatively with api_key and resource_instance_id.
The above cell can be replaced with:

conn_meta_props= {
    client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {db_name} ",
    client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(db_name),
    client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
    client.connections.ConfigurationMetaNames.PROPERTIES: {
        'bucket': bucket_name,
        'api_key': cos_credentials['apikey'],
        'resource_instance_id': cos_credentials['resource_instance_id'],
        'iam_url': 'https://iam.cloud.ibm.com/identity/token',
        'url': 'https://s3.us.cloud-object-storage.appdomain.cloud'
    }
}

conn_details = client.connections.create(meta_props=conn_meta_props)

Define connection information to training data.

Check the connection information. Upload the data and validate.

Optimizer configuration

Provide the input information for AutoAI optimizer:

Configuration parameters can be retrieved via get_params().

3. Experiment run

Call the fit() method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying background_model=True.

You can use the get_run_status() method to monitor AutoAI jobs in background mode.

4. Pipelines comparison and testing

You can list trained pipelines and evaluation metrics information in the form of a Pandas DataFrame by calling the summary() method. You can use the DataFrame to compare all discovered pipelines and select the one you like for further testing.

You can visualize the scoring metric calculated on a holdout data set.

Get selected pipeline model

Download and reconstruct a scikit-learn pipeline model object from the AutoAI training job.

Check confusion matrix for selected pipeline.

Check features importance for selected pipeline.

Convert the pipeline model to a Python script and download it

Visualize pipeline

Each node in the visualization is a machine-learning operator (transformer or estimator). Each edge indicates data flow (transformed output from one operator becomes input to the next). The input to the root nodes is the initial dataset and the output from the sink node is the final prediction. When you hover the mouse pointer over a node, a tooltip shows you the configuration arguments of the corresponding operator (tuned hyperparameters). When you click on the hyperlink of a node, it brings you to a documentation page for the operator.

Pipeline source code

In the pretty-printed code, >> is the pipe combinator (dataflow edge) and & is the and combinator (combining multiple subpipelines). They correspond to the make_pipeline and make_union functions from scikit-learn, respectively. If you prefer the functions, you can instead pretty-print your pipeline with best_pipeline.pretty_print(ipython_display=True, combinators=False).

Reading training data from COS

Test pipeline model locally

5. Historical runs

In this section you learn to work with historical AutoPipelines fit jobs (runs).

To list historical runs use method list().

Note: You can filter runs by providing experiment name.

To work with historical pipelines found during a particular optimizer run, you need to first provide the run_id to select the fitted optimizer.

Note: you can assign selected run_id to the run_id variable.

Get executed optimizer's configuration parameters

Get historical optimizer instance and training details

List trained pipelines for selected optimizer

Get selected pipeline and test locally


6. Pipeline refinement with Lale and testing

In this section you learn how to refine and retrain the best pipeline returned by AutoAI. There are many ways to refine a pipeline. For illustration, simply replace the final estimator in the pipeline by an interpretable model. The call to wrap_imported_operators() augments scikit-learn operators with schemas for hyperparameter tuning.

Pipeline decomposition and new definition

Start by removing the last step of the pipeline, i.e., the final estimator.

Next, add a new final step, which consists of a choice of three estimators. In this code, | is the or combinator (algorithmic choice). It defines a search space for another optimizer run.

New optimizer Hyperopt configuration and training

To automatically select the algorithm and tune its hyperparameters, we create an instance of the Hyperopt optimizer and fit it to the data.

Pipeline model tests and visualization

7. Deploy and Score

In this section you will learn how to deploy and score pipeline model as webservice using WML instance.

Online deployment creation

Deployment object could be printed to show basic information:

To show all available information about the deployment use the .get_params() method:

Scoring of webservice

You can make scoring request by calling score() on deployed pipeline.

If you want to work with the web service in an external Python application you can retrieve the service object by:

After that you can call service.score() method.

Deleting deployment

You can delete the existing deployment by calling the service.delete() command. To list the existing web services you can use service.list().

Batch deployment creation

A batch deployment processes input data from a inline data and return predictions in scoring details.

Create batch deployment for Pipeline_2 created in AutoAI experiment with the run_id.

Score batch deployment with inline payload as pandas DataFrame.

8. Clean up

If you want to clean up all created assets:

please follow up this sample notebook.

9. Summary and next steps

You successfully completed this notebook!.

You learned how to use ibm-watson-machine-learning to run AutoAI experiments.

Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.

Authors

Lukasz Cmielowski, PhD, is an Automation Architect and Data Scientist at IBM with a track record of developing enterprise-level applications that substantially increases clients' ability to turn data into actionable knowledge.

Amadeusz Masny, Python Software Developer in Watson Machine Learning at IBM

Kiran Kate, Senior Software Engineer at IBM Research AI

Martin Hirzel, Research Staff Member and Manager at IBM Research AI

Jan Sołtysik, Intern in Watson Machine Learning

Copyright © 2020, 2021 IBM. This notebook and its source code are released under the terms of the MIT License.